/* eslint-disable no-param-reassign */
import DrawerFooter from '@/components/DrawerFooter';
import { useStore } from '@/hooks';
import { Button, Dialog, Form, Input, Message } from '@alifd/next';
import { t } from '@lingui/macro';
import { observable } from 'mobx';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import { FieldsGrid, TitleGrid } from '../stores/definitions';
import { apiLbs } from '@/services';
import { deconstructionMapObj, arrTransferObj } from '@/utils/util';
import MapModal from '@/components/MapModal';
import CurrentTable from './CurrentTable';
import NewTable from './NewTable';

const FromItem = Form.Item;

function DataForm({ id, modal, onSubmit, onCancel }) {
  const { busStationStore: store } = useStore();
  const [station] = useState(() => observable({}));
  const [isViewMode] = useState(modal[0] === 'view');
  const [map, setMap] = useState({ show: false, coord: '', cityName: '' });
  const formProps = isViewMode ? { field: false } : {};
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const objRef = useRef();

  useEffect(() => { if (modal.close?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    (async () => {
      if (id) {
        const data = await store.get(id);
        store.stationInfo = data;
        editCtx.origin = _.cloneDeep(data);
        _.assign(station, data);
      }
    })();
    return () => {
      store.selectStation = [];
      store.selectStationInfos = [];
      store.currentStationInfos = [];
    };
  }, []);

  if (!station) return <></>;

  const overrideModel = {
    longLat: {
      ui: {
        renderer: (v, i, r) => <Input value={v} addonAfter={<Button type="primary" onClick={() => handleMapOpen(r)}>{t`获取经纬度`}</Button>} />,
      },
    },
  };

  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(station, name, value);
    if (name === 'cityId') {
      const labels = item.field.fieldsMeta.cityId?.inputValues[2] || [];
      _.set(station, 'cityName', labels?.label);
    }
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleMapOpen = async () => {
    const tempStation = toJS(station);
    const { name, cityName } = tempStation || {};
    if (!name) {
      Message.error({ content: t`请输入名称!` });
      return;
    }
    if (!cityName) {
      Message.error({ content: t`请选择城市!` });
      return;
    }
    objRef.current = tempStation;
    let coord = station?.longLat;
    const currentCity = cityName;
    if (!coord) {
      const r = await apiLbs.placeSearch({ region: currentCity, keyword: name });
      const { location } = r?.[0] || {};
      const { lat, lng } = arrTransferObj(location);
      coord = deconstructionMapObj({ lat, lng });
    }
    setMap({ show: true, coord, cityName: currentCity });
  };

  const handleCoordPicked = async (coord) => {
    const _coord = deconstructionMapObj(coord);
    _.set(station, 'longLat', _coord);
    setMap({ show: false });
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  const handleSubmit = (__, errors, ___) => {
    if (!_.isEmpty(errors)) {
      console.log('🚀 _ file: DataForm.jsx:93 _ errors:', errors);
      return;
    }
    onSubmit?.(station);
  };

  return (
    <Form
      isPreview={isViewMode}
      {...formProps}
      value={station}
      colon
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <TitleGrid title={t`站点信息`} />
      <FieldsGrid
        formData={station}
        mode={modal[0]}
        overrideModel={overrideModel}
        fields={['name', 'cityId', 'areaName', 'type', 'onAddress', 'offAddress', 'longLat']}
      />
      <TitleGrid title={t`已关联第三方站点信息`} />
      <CurrentTable data={station?.siteMapping} />
      <TitleGrid title={t`第三方站点信息`} />
      <NewTable />
      <DrawerFooter>
        <FromItem>
          {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
      <MapModal
        visible={map.show}
        coord={map.coord}
        cityName={map.cityName}
        fullId={map?.fullId}
        containerId={'busStation'}
        onClose={() => setMap({ show: false })}
        onCancel={() => setMap({ show: false })}
        onPick={handleCoordPicked}
      />
    </Form>
  );
}

export default observer(DataForm);
